/**
 * ━━━━━━神兽出没━━━━━━
 * 　　　┏┓　　　┏┓
 * 　　┏┛┻━━━┛┻┓
 * 　　┃　　　　　　　┃
 * 　　┃　　　━　　　┃
 * 　　┃　┳┛　┗┳　┃
 * 　　┃　　　　　　　┃
 * 　　┃　　　┻　　　┃
 * 　　┃　　　　　　　┃
 * 　　┗━┓　　　┏━┛
 * 　　　　┃　　　┃神兽保佑, 永无BUG!
 * 　　　　┃　　　┃Code is far away from bug with the animal protecting
 * 　　　　┃　　　┗━━━┓
 * 　　　　┃　　　　　　　┣┓
 * 　　　　┃　　　　　　　┏┛
 * 　　　　┗┓┓┏━┳┓┏┛
 * 　　　　　┃┫┫　┃┫┫
 * 　　　　　┗┻┛　┗┻┛
 * ━━━━━━感觉萌萌哒━━━━━━
 */
package com.zkgengkun.console.service.impl;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.zkgengkun.console.service.UploadService;
import com.zkgengkun.constant.SysConstants;
import com.zkgengkun.domain.MyFile;
import com.zkgengkun.repository.MyFileRepository;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author gengshikun
 * @date 2017/2/15
 */
@Service("uploadService")
public class UploadServiceImpl implements UploadService {

    private static final Logger logger = LoggerFactory.getLogger(UploadServiceImpl.class);

    public static final Long KB = 1024L;
    public static final Long MB = 1024L * 1024L;
    public static final Long GB = 1024L * 1024L * 1024L;

    @Value("${file_path}")
    private String file_path;

    @Value("${file_url}")
    private String file_url;

    @Autowired
    private MyFileRepository myFileRepository;

    /**
     * 上传单个文件
     *
     * @param files
     * @return
     */
    @Override
    public List<Map> submitImage(MultipartFile[] files) {
        List<Map> results = Lists.newArrayList();
        Map<String, Object> result = Maps.newHashMap();
        MyFile myFile = null;
        for (MultipartFile file : files) {
            if (file.getSize() > 2 * MB) {
                result.put("sizeMsg", "文件大小不超过2M");
                result.put("status", Boolean.FALSE);
                results.add(result);
                continue;
            }

            //  判断文件类型
            String fileType = file.getContentType();
            if (StringUtils.isNotBlank(fileType)) {
                if (fileType.matches(".*wordprocessingml.document$") || fileType.matches(".*msword$")) {  //word
                    result.put("type", SysConstants.FILE_TYPE_WORD);
                    fileType = SysConstants.FILE_TYPE_WORD;
                } else if (fileType.matches(".*presentationml.presentation$") || fileType.matches(".*ms-powerpoint$")) { //ppt
                    result.put("type", SysConstants.FILE_TYPE_PPT);
                    fileType = SysConstants.FILE_TYPE_PPT;
                } else if (fileType.matches("application/pdf")) {  //pdf
                    result.put("type", SysConstants.FILE_TYPE_PDF);
                    fileType = SysConstants.FILE_TYPE_PDF;
                } else if (fileType.matches(".*spreadsheetml.sheet$") || fileType.matches(".*ms-excel$")) {  //excel
                    result.put("type", SysConstants.FILE_TYPE_EXCEL);
                    fileType = SysConstants.FILE_TYPE_EXCEL;
                } else if (fileType.matches("^image.*")) {  //image
                    result.put("type", SysConstants.FILE_TYPE_IMAGE);
                    fileType = SysConstants.FILE_TYPE_IMAGE;
                } else {  //other
                    result.put("type", SysConstants.FILE_TYPE_OTHER);
                    fileType = SysConstants.FILE_TYPE_OTHER;
                }
            }

            result.put("fileName", file.getOriginalFilename().toString());
            result.put("size", file.getSize());


            String[] arrayName = file.getOriginalFilename().split("\\.");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String filePath = System.getProperty("user.dir") + this.file_path;
            String fileUrl = this.file_url + File.separator + sdf.format(new Date()) + File.separator + System.currentTimeMillis() + "." + arrayName[arrayName.length - 1];
            try {
                File newFile = new File(filePath + fileUrl);
                FileUtils.copyInputStreamToFile(file.getInputStream(), newFile);
                BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(newFile));
                byte[] bytes = file.getBytes();
                stream.write(bytes);
                stream.close();
                result.put("fileUrl", fileUrl);
                result.put("data", "data:image/jpeg|png|gif;base64," + new BASE64Encoder().encode(bytes));
                result.put("status", Boolean.TRUE);

                myFile = new MyFile();
                myFile.setName(file.getOriginalFilename().toString());
                myFile.setType(fileType);
                myFile.setSize(file.getSize());
                myFile.setPath(fileUrl);
                myFile.setDeleteBoolean(Boolean.FALSE);
                myFileRepository.saveAndFlush(myFile);

                results.add(result);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return results;
    }


    public String uploadJpgByUrl(String url) {
        DataInputStream dataInputStream = null;
        try {
            URL sendUrl = new URL(url);
            dataInputStream = new DataInputStream(sendUrl.openStream());
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String filePath = System.getProperty("user.dir") + this.file_path;
            String fileUrl = this.file_url + File.separator + dateFormat.format(new Date())
                    + File.separator + System.currentTimeMillis() + ".jpg";

            File file = new File(filePath + fileUrl);
            FileUtils.copyInputStreamToFile(dataInputStream, file);

            return filePath + fileUrl;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != dataInputStream) {
                    dataInputStream.close();
                }
            } catch (IOException e) {
                logger.error(">>>>>>>>>关闭IOException:{}", e);
            }
        }
        return null;
    }
}
